<?php

namespace app\admin\server;

use think\Env;
use think\Exception;
use think\Loader;
use WXBizMsgCrypt;

Loader::import('weworkapi_php-master.callback.WXBizMsgCrypt');// 括号中为类库路径
class QiweiServer extends BaseServer
{
    protected $kefu_token;
    protected $kefu_encodingAESKey;
    protected $corpId;
    protected $kefu_Secret;
    protected $txl_Secret;
    protected $txl_Token;
    protected $txl_EncodingAESKey;
    public function __construct()
    {
        $this->kefu_token = Env::get('qiwei.kefu_token', '');
        $this->kefu_encodingAESKey = Env::get('qiwei.kefu_EncodingAESKey', '');
        $this->corpId = Env::get('qiwei.CorpId', '');
        $this->kefu_Secret = Env::get('qiwei.kefu_Secret', '');

        $this->txl_Secret = Env::get('qiwei.Txl_Secret', '');//通讯录同步
        $this->txl_Token = Env::get('qiwei.Txl_Token', '');//通讯录同步
        $this->txl_EncodingAESKey = Env::get('qiwei.Txl_EncodingAESKey', '');//通讯录同步
    }

    /***
     * 检验消息的真实性，并且获取解密后的明文.
     * application/library/weworkapi_php-master/callback/Sample.php
     * @param $echostr
     * @param $msg_signature
     * @param $timestamp
     * @param $nonce
     * @return string
     * @throws Exception
     */
    public function VerifyURL($echostr, $msg_signature, $timestamp, $nonce)
    {
        // file_put_contents('./result.txt', '');
        // file_put_contents('./result.txt', 'start:'.date('Y-m-d H:i:s').PHP_EOL, FILE_APPEND | LOCK_EX);
        try {
            $wxcpt = new WXBizMsgCrypt($this->kefu_token, $this->kefu_encodingAESKey, $this->corpId);
            $sMsg = '';
            // file_put_contents('./result.txt', '1'.PHP_EOL, FILE_APPEND | LOCK_EX);
            $errCode = $wxcpt->VerifyURL($msg_signature, $timestamp, $nonce, $echostr, $sMsg);
            // file_put_contents('./result.txt', '$errCode='.$errCode.PHP_EOL, FILE_APPEND | LOCK_EX);
            // file_put_contents('./result.txt', '$sMsg='.$sMsg.PHP_EOL, FILE_APPEND | LOCK_EX);
            if($errCode == 0) {
                /*  var_dump($sMsg);
                  echo $echostr;*/
                return $sMsg;
            }
                /* print("ERR: " . $errCode . "\n\n");*/
            throw new Exception($sMsg, $errCode);
        } catch(\Exception $e) {
            // file_put_contents('./result.txt', 'decryptMsg_error='.$e->getMessage().PHP_EOL, FILE_APPEND | LOCK_EX);
            throw new Exception($e->getMessage());
        }
        // file_put_contents('./result.txt', 'end:'.date('Y-m-d H:i:s').PHP_EOL, FILE_APPEND | LOCK_EX);
    }
    public function DoVerifyURLTxl($echostr, $msg_signature, $timestamp, $nonce)
    {
        // file_put_contents('./result.txt', '');
        // file_put_contents('./result.txt', 'start:'.date('Y-m-d H:i:s').PHP_EOL, FILE_APPEND | LOCK_EX);
        try {
            $wxcpt = new WXBizMsgCrypt($this->txl_Token, $this->txl_EncodingAESKey, $this->corpId);
            $sMsg = '';
            // file_put_contents('./result.txt', '1'.PHP_EOL, FILE_APPEND | LOCK_EX);
            $errCode = $wxcpt->VerifyURL($msg_signature, $timestamp, $nonce, $echostr, $sMsg);
            // file_put_contents('./result.txt', '$errCode='.$errCode.PHP_EOL, FILE_APPEND | LOCK_EX);
            // file_put_contents('./result.txt', '$sMsg='.$sMsg.PHP_EOL, FILE_APPEND | LOCK_EX);
            if($errCode == 0) {
                /*  var_dump($sMsg);
                  echo $echostr;*/
                return $sMsg;
            }
            /* print("ERR: " . $errCode . "\n\n");*/
            throw new Exception($sMsg, $errCode);
        } catch(\Exception $e) {
            // file_put_contents('./result.txt', 'decryptMsg_error='.$e->getMessage().PHP_EOL, FILE_APPEND | LOCK_EX);
            throw new Exception($e->getMessage());
        }
        // file_put_contents('./result.txt', 'end:'.date('Y-m-d H:i:s').PHP_EOL, FILE_APPEND | LOCK_EX);
    }


    /////////////////////////////////////////////客服//////////////////////////////////////////////////////////
    // 获取客服账号列表
    public static function getKfAccountList()
    {
        try {
            $access_token = WxworkAccessTokenServer::getWxworkAccessToken();
        } catch(Exception $e) {
            throw new Exception($e->getMessage());
        }
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/kf/account/list?access_token=' . $access_token;
        $data = ['offset' => 0, 'limit' => 100];
        $result = self::httpCurlPostRequest($url, $data);
        if(empty($result) || !isset($result['errcode']) || !isset($result['account_list']) || $result['errcode'] !== 0) {
            throw new Exception('获取客服账号失败');
        }
        /**
         * account_list
         * array (size=2)
         * 0 =>
         * array (size=4)
         * 'open_kfid' => string 'wkDraDcwAAB_giuRddh2t60R0VuOwZHQ' (length=32)
         * 'name' => string '重庆财优商务信息咨询服务有限公司客服' (length=54)
         * 'avatar' => string 'https://wwcdn.weixin.qq.com/node/wework/images/kf_head_image_url_1.png' (length=70)
         * 'manage_privilege' => boolean false
         * 1 =>
         * array (size=4)
         * 'open_kfid' => string 'wkDraDcwAAVCNiUP4R4C1tFWq7T42pbg' (length=32)
         * 'name' => string '客服00001' (length=11)
         * 'avatar' => string 'https://wwcdn.weixin.qq.com/node/wework/images/avatar3.20e095035c.png' (length=69)
         * 'manage_privilege' => boolean false
         */
        return $result['account_list'];
    }

    //////////////////////////////////////接待人员//////////////////////////////////////////////////////////////////////////
    //获取接待人员列表
    public static function getKfServicerList($open_kfid = 'wkDraDcwAAVCNiUP4R4C1tFWq7T42pbg')
    {
        try {
            $access_token = WxworkAccessTokenServer::getWxworkAccessToken();
        } catch(Exception $e) {
            throw new Exception($e->getMessage());
        }
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/kf/servicer/list?access_token=' . $access_token . '&open_kfid=' . $open_kfid;
        $result = self::httpCurlGetRequest($url);
        if(empty($result) || !isset($result['errcode']) || !isset($result['servicer_list']) || $result['errcode'] !== 0) {
            throw new Exception('获取接待人员列表失败');
        }
        /**
         * servicer_list
         * array (size=1)
         * 0 =>
         * array (size=2)
         * 'userid' => string 'JianLiHua' (length=9)
         * 'status' => int 0
         */
        return $result['servicer_list'];
    }

    //////////////////////////////////////////////会话分配与消息收发///////////////////////////////////////////////////////////////

    /// 获取会话状态
    public static function getKfServiceState($open_kfid, $external_userid)
    {
        try {
            $access_token = WxworkAccessTokenServer::getWxworkAccessToken();
        } catch(Exception $e) {
            throw new Exception($e->getMessage());
        }
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/kf/service_state/get?access_token=' . $access_token;
        $data = ['open_kfid' => $open_kfid, 'external_userid' => $external_userid];
        $result = self::httpCurlPostRequest($url, $data);
        if(empty($result) || !isset($result['errcode']) || !isset($result['servicer_userid']) || $result['errcode'] !== 0) {
            throw new Exception('获取客服账号失败');
        }
        /**
         * {
         * "errcode": 0,
         * "errmsg": "ok",
         * "service_state": 3,
         * "servicer_userid": "zhangsan"
         * }
         */
        //service_state
        return $result['service_state'];
    }

    //////////////////获取客户基础信息////////////////////

    /**
     * 获取客户基础信息
     * @param array $external_userid_list           external_userid 列表
     *                                              可填充个数：1 ~ 100。超过100个需分批调用。
     * @param bool  $need_enter_session_context     否需要返回客户48小时内最后一次进入会话的上下文信息。
     *                                              0-不返回 1-返回。默认不返回
     * @return mixed|string
     * @throws Exception
     */
    public static function getKfCustomerBatchget(array $external_userid_list, bool $need_enter_session_context = false)
    {
        if(empty($external_userid_list)) {
            throw new Exception('获取获取客户基础信息-参数错误');
        }
        try {
            $access_token = WxworkAccessTokenServer::getWxworkAccessToken();
        } catch(Exception $e) {
            throw new Exception($e->getMessage());
        }
        $url = ' https://qyapi.weixin.qq.com/cgi-bin/kf/customer/batchget?access_token=' . $access_token;
        $need_enter_session_context = $need_enter_session_context ? 1 : 0;
        $data = ['external_userid_list' => $external_userid_list, 'need_enter_session_context' => $need_enter_session_context];
        $result = self::httpCurlPostRequest($url, $data);
        if(empty($result) || !isset($result['errcode']) || !isset($result['customer_list']) || !isset($result['invalid_external_userid']) || $result['errcode'] !== 0) {
            throw new Exception('获取获取客户基础信息失败');
        }
        unset($result['errcode']);
        unset($result['errmsg']);
        /**
         * {
         * "errcode": 0,
         * "errmsg": "ok",
         * "customer_list": [
         * {
         *      "external_userid": "wmxxxxxxxxxxxxxxxxxxxxxx",
         *      "nickname": "张三",
         *      "avatar": "http://xxxxx",
         *      "gender": 1,
         *      "unionid": "oxasdaosaosdasdasdasd",
         *      "enter_session_context": {
         *          "scene": "123",
         *          "scene_param": "abc",
         *          "wechat_channels": {
         *              "nickname": "进入会话的视频号名称",
         *              "scene": 1
         *          }
         *      }
         * }
         * ],
         * "invalid_external_userid": [
         *      "zhangsan"
         * ]
         * }
         */
        return $result;
    }
}